<?php
namespace Biz\service\activity;

use Biz\model\activity\AllActivityGoods;
use Biz\model\activity\AllActivitySku;
use Biz\service\Goods;
use Biz\service\Sku as sSku;
use Biz\model\activity\NewCommerExclusiveSku as mNewCommerExclusiveSku;
use Biz\model\activity\NewCommerExclusive as mNewCommerExclusive;
use Biz\service\Sku;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\model\activity\NewComer as mNewComer;
use Biz\module\Classes\adm\NewComerExcel;
use Biz\service\SearchGoods;
use Biz\service\esSearch\Goods as esGoods;
/**
 * @deprecated
 */
class NewComer
{

	public static function admSaveGoods($startTime, $endTime ,$goodsIds, $adminUid)
	{
		$goodsIds = preg_split("/\s/", $goodsIds);
		$goodsIds = array_filter($goodsIds);
		if (!$goodsIds) {
			throw new \Exception('请填写正确的商品ID');
		}

        list($goodsIds, $invalidateData) = AllactivityInfoBak::admCheckActivityTime(
            $goodsIds,
            ['start_time' => $startTime, 'end_time'=> $endTime],
            AllactivityInfoBak::ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE
        );

		if ($invalidateData) {
			foreach ($invalidateData as $invalidateDatum) {
				throw new \Exception('相同时间内存在相同的活动商品，商品ID：' . $invalidateDatum['goods_id']);
			}
		}

		$skuInfos = sSku::Sku($goodsIds, sSku::FIELDS_GROUP_SKU_INFO);

		return mNewCommerExclusive::action(function () use ($startTime, $endTime, $goodsIds, $adminUid, $skuInfos) {
			foreach ($goodsIds as $goodsId) {
				mNewCommerExclusive::insert([
					'goods_id' => $goodsId,
					'start_time' => $startTime,
					'end_time' => $endTime,
					'add_time' => date("Y-m-d H:i:s"),
					'edit_time' => date("Y-m-d H:i:s"),
					'admin_uid' => $adminUid,
					'status' => mNewCommerExclusive::STATUS_NO_PRICE
				]);
				$exclusiveId = mNewCommerExclusive::id();
				if (!$exclusiveId) {
					throw new \Exception('商品ID' . $goodsId . '插入数据库失败');
				}

				$insertData = [];
				foreach ($skuInfos[$goodsId] as $skuInfo) {
					$insertData[] = [
						'goods_id' => $goodsId,
						'exclusive_id' => $exclusiveId,
						'sku_id' => $skuInfo['sku_id'],
						'start_time' => $startTime,
						'end_time' => $endTime,
					];
				}
				$rowCount = mNewCommerExclusiveSku::insertData($insertData, $adminUid);
				if (!$rowCount) {
					throw new \Exception('商品ID' . $goodsId . '插入数据库失败');
				}
			}
			return true;
		});
	}

	public static function admDel($id, $goodsid)
	{
		return mNewCommerExclusive::action(function() use ($id, $goodsid) {
			$status = mNewCommerExclusive::get('status', ['id' => $id]);
			$result = mNewCommerExclusive::update([
				'edit_time' => date("Y-m-d H:i:s"),
				'status' => mNewCommerExclusive::STATUS_DELETE
			], [
				'id' => $id
			]);
			if ($result -> rowCount()) {
				$resutl = mNewCommerExclusiveSku::update([
					'edit_time' => date('Y-m-d H:i:s'),
					'status' => mNewCommerExclusiveSku::STATUS_DELETE
				], [
					'exclusive_id' => $id
				]);
				if (!$resutl->rowCount()) {
					throw new \Exception('sku数据库更新失败');
				}
				 $results = AllActivityInfo::admDelActivityInfo($id,AllActivityInfo::ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE, AllActivityInfo::ALL_ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE);
                return $results;
			} else {
				throw new \Exception('数据库更新失败');
			}
		});

	}

	public static function admInfo($id, $goodsId)
	{
		$excluInfo = mNewCommerExclusiveSku::getInfos($id, $goodsId);
		$activityPrice = array_column($excluInfo, 'activity_price', 'sku_id');
		$goodsInfo = Goods::Goods([$goodsId], Goods::FIELDS_GROUP_DETAIL)[$goodsId];
		$skuInfos = sSku::Sku([$goodsId], sSku::FIELDS_GROUP_ALL)[$goodsId];
		$skuInfos = array_column($skuInfos['sku_info'], null, 'sku_id');

		$returnRst = [
			'id' => $goodsInfo['id'],
			'cover_img' => $goodsInfo['cover_img'],
			'title' => $goodsInfo['title'],
			'skus' => [],
            'start_time' => current($excluInfo)['start_time'],
            'end_time' => current($excluInfo)['end_time'],
		];
		foreach ($activityPrice as $skuId => $activityprice) {
			$returnRst['skus'][] = [
				'sku_id' => $skuId,
                'sku_desc' => $skuInfos[$skuId]['sku_desc'],
				'ori_price' => $skuInfos[$skuId]['ori_price'],
				'activity_price' => $activityprice,
				'subsidy' => $skuInfos[$skuId]['ori_price'] - $activityprice
			];
		}

		return $returnRst;
	}

	public static function admSubConfirm($id, $goodsId, $activityPrice)
	{
        // 根据id和goodsid查询时间 查询到时间之后进行验证
        $checkGoodsList[$goodsId] = $activityPrice;

        $rows = mNewCommerExclusive::get('*', ['id' => $id]);
        $activityInfo = [
            'start_time' => $rows['start_time'],
            'end_time' => $rows['end_time'],
        ];

        $result = AllactivityInfoBak::admCheckActivityPrice($checkGoodsList, $activityInfo, AllactivityInfoBak::ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE);
        if(end($result)) {
            $skuInfos = sSku::Sku([$goodsId], sSku::FIELDS_GROUP_ALL);
            $skuInfos = array_column($skuInfos[$goodsId]['sku_info'], null, 'sku_id');
            $invalidPriceData = end($result);
            $data = reset($invalidPriceData);
            throw new \Exception('sku ' . $skuInfos[$data['sku_id']]['sku_desc'] . ' 的新人专享价 ' . $activityPrice[$data['sku_id']] . ' 高于同时段的商家直降价 ' . $data['activity_price'] . ' ，请修改后再保存', 1);
        }

		foreach ($activityPrice as $skuId => $price) {
			if (!$price) {
				throw new \Exception('请补全活动价', 1);
			}
		}
		$skuInfos = Sku::Sku([$goodsId], Sku::FIELDS_GROUP_SKU_INFO);
		$confirm = [];
		foreach ($skuInfos[$goodsId] as  $skuInfo) {
			foreach ($activityPrice as $skuId => $price) {
				if ($price / $skuInfo['ori_price'] < 0.9) {
					$confirm[] = "skuId: " .$skuId . " 活动价低于9折";
				}
			}
		}
		if ($confirm) {
			$confirm[] = "是否继续提交 ???";
			throw new \Exception(implode("\r\n", $confirm), 2);
		}
		return true;
	}

	public static function admSetActivityPrice($id, $goodsId, $activityPrice, $adminUid)
	{
		foreach ($activityPrice as $skuId => $price) {
			if (!$price) {
				throw new \Exception('请补全活动价');
			}
		}

		return mNewCommerExclusive::action(function () use ($id, $goodsId, $activityPrice, $adminUid) {
			 $result = mNewCommerExclusive::update([
				'edit_time' => date('Y-m-d H:i:s'),
				'status' => mNewCommerExclusive::STATUS_NORMAL
			], [
				'id' => $id,
				'goods_id' => $goodsId
			]);
			if ($result->rowCount()) {
				foreach ($activityPrice as $skuId => $price) {
					$result = mNewCommerExclusiveSku::update([
						'edit_time' => date('Y-m-d H:i:s'),
						'activity_price' => $price,
						'status' => mNewCommerExclusiveSku::STATUS_NORMAL
					], [
						'exclusive_id' => $id,
						'goods_id' => $goodsId,
						'sku_id' => $skuId
					]);
					if (!$result->rowCount()) {
						throw new \Exception('sku数据库更新失败');
					}
				}

				list($activityGoodsData, $activitySkuData) = self::formatAllActivityInfo($id, $goodsId);
				return AllActivityInfo::admUpdateActivityInfo($id, AllActivityInfo::ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE,$activityGoodsData,$activitySkuData, AllActivityInfo::ALL_ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE);
			} else {
				throw new \Exception('数据库更新失败');
			}
			return true;
		});
	}

	private static function formatAllActivityInfo($id, $goodsId)
	{
		$activityGoodsData = [];
		$activitySkuData = [];
		$exclusives = mNewCommerExclusiveSku::getInfos($id, $goodsId, true);
		$goodsInfo = Goods::Goods([$goodsId],Goods::FIELDS_GROUP_DETAIL)[$goodsId];
		$skuInfos = Sku::Sku([$goodsId], Sku::FIELDS_GROUP_SKU_INFO)[$goodsId];
		$skuInfos = array_column($skuInfos, null, 'sku_id');
		$activityGoodsData[] = [
			'activity_id' => $id,
			'shop_id' => $goodsInfo['shop_info']['shop_id'],
			'goods_id' => $goodsId,
			'type' => ActivityInfo::ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE,
			'start_time' => $exclusives[0]['start_time'],
			'end_time' => $exclusives[0]['end_time'],
			'status' => AllActivityGoods::STATUS_NORMAL,
			'preview_start_time' => $exclusives[0]['start_time'],
			'real_start_time' => $exclusives[0]['start_time'],
			'real_end_time' => $exclusives[0]['end_time'],
		];

		foreach ($exclusives as $item) {
			$activitySkuData[] = [
				'activity_id' => $id,
				'shop_id' => $goodsInfo['shop_info']['shop_id'],
				'type' => ActivityInfo::ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE,
				'goods_id' => $goodsId,
				'sku_id' => $item['sku_id'],
				'status' => AllActivitySku::STATUS_NORMAL,
				'is_activity_stock' => AllActivitySku::NOT_USE_ACTIVITY_STOCK,
//				'activity_stock' => $skuInfos['start_stock'],
				'actual_stock' => $skuInfos[$item['sku_id']]['stock'],
				'activity_price' => $item['activity_price'],
				'is_activity_commission' => AllActivitySku::NOT_USE_COMMISSION,
//				'activity_commission' => $limitRobInfo['commission'],
				'start_time' => $item['start_time'],
				'end_time' => $item['end_time'],
				'preview_start_time' => $item['start_time'],
				'real_start_time' => $item['start_time'],
				'real_end_time' => $item['end_time'],
				'limit_buy_count' => 1,
				'activity_allowance' => $skuInfos[$item['sku_id']]['ori_price'] - $item['activity_price'],
			];
		}
		return [$activityGoodsData, $activitySkuData];
	}

	public static function admList($page, $params, $pagesize = 20)
	{
        $where = self::buildWhere($params);
        $defaultWhere = ['status' =>
            [mNewCommerExclusive::STATUS_NORMAL,
            mNewCommerExclusive::STATUS_NO_PRICE]
        ];

        if($where) {
            $defaultWhere = array_merge($defaultWhere, $where);
        }

		$infoList = mNewCommerExclusive::select('*', [
            'AND' => $defaultWhere,
			'ORDER' => ['id'=> 'DESC'],
			'LIMIT' => [($page - 1) * $pagesize, $pagesize]
		]);


        foreach ($infoList as $value) {
            if(strtotime($value['start_time']) >= time() && strtotime($value['end_time']) >= time()) {
                $isUpdate[$value['id']] = 1;
            } else if(strtotime($value['start_time']) <= time() && strtotime($value['end_time']) >= time()) {
                $isUpdate[$value['id']] = 1;
            } else {
                $isUpdate[$value['id']] = 0;
            }
        }

        $count = mNewCommerExclusive::count('*', $defaultWhere);
		$infoList = mNewCommerExclusiveSku::select('*', [
			'exclusive_id' => array_column($infoList, 'id'),
			'status' => [
				mNewCommerExclusive::STATUS_NORMAL,
				mNewCommerExclusive::STATUS_NO_PRICE
			],
			'ORDER' => ['end_time'=> 'DESC'],
		]);
		$infoListGrpByExId = [];
		foreach ($infoList as $item) {
			$infoListGrpByExId[$item['exclusive_id']][$item['goods_id']][$item['sku_id']] = $item;
		}

		$goodsInfos = Goods::Goods(array_column($infoList, 'goods_id'), Goods::FIELDS_GROUP_DETAIL);
		$skuInfos = sSku::Sku(array_column($infoList, 'goods_id'), sSku::FIELDS_GROUP_SKU_INFO);
		$returnList = [];
		foreach ($infoListGrpByExId as $exclusiveId => $infoList) {
			foreach ($infoList as $goodsId => $item) {
			    if (!isset($goodsInfos[$goodsId])) {
			        continue;
                }
				$returnList[$exclusiveId] = [
					'id' => $exclusiveId,
					'shop_name' => $goodsInfos[$goodsId]['shop_info']['shop_name'],
					'shop_id' => $goodsInfos[$goodsId]['shop_info']['shop_id'],
					'cover_img' => $goodsInfos[$goodsId]['cover_img'],
					'goods_id' => $goodsInfos[$goodsId]['id'],
					'title' => $goodsInfos[$goodsId]['title'],
					'ori_max_price' => max(array_column($skuInfos[$goodsId], 'ori_price')),
					'ori_min_price' => min(array_column($skuInfos[$goodsId], 'ori_price')),
					'stock' => array_sum(array_column($skuInfos[$goodsId], 'stock')),
					'activity_max_price' => max(array_column($infoListGrpByExId[$exclusiveId][$goodsId], 'activity_price')),
					'activity_min_price' => min(array_column($infoListGrpByExId[$exclusiveId][$goodsId], 'activity_price')),
				];
				$returnList[$exclusiveId]['subsidy'] = [];
				$skuInfos[$goodsId] = array_column($skuInfos[$goodsId], null, 'sku_id');
                $returnList[$exclusiveId]['time_range'] ='';
				foreach ($skuInfos[$goodsId] as $skuId => $skuInfo) {
					if (isset($infoListGrpByExId[$exclusiveId][$goodsId][$skuId])) {
						if($infoListGrpByExId[$exclusiveId][$goodsId][$skuId]['status'] == mNewCommerExclusiveSku::STATUS_NORMAL) {
							$returnList[$exclusiveId]['subsidy'][] = $skuInfo['ori_price'] - $infoListGrpByExId[$exclusiveId][$goodsId][$skuId]['activity_price'];
						}
						$returnList[$exclusiveId]['time_range'] = $infoListGrpByExId[$exclusiveId][$goodsId][$skuId]['start_time'] . " - " . $infoListGrpByExId[$exclusiveId][$goodsId][$skuId]['end_time'];
					}
				}
			}
            $returnList[$exclusiveId]['is_update'] = $isUpdate[$exclusiveId];
		}

		return ['list' => $returnList, 'count' => $count];
	}

	public static function mgtNewcommerTags($goodsIds)
	{
		$rst = [];
		$Exclusives = mNewCommerExclusive::getNotOverList($goodsIds);
		foreach ($Exclusives as $goodsId => $exclusive) {
			if (in_array($goodsId, $goodsIds)) {
				foreach ($exclusive as $item) {
					$rst[$goodsId][] = "新人专享 " ;
				}
			}
		}
		return $rst;

	}

    /**
     * 拼装where条件
     * @param $params
     * @return array
     */
    private static function buildWhere($params)
    {
        $where = [];
        // 商品信息搜索条件
        if (isset($params['field1']) && $params['field1']) {
            if ($params['keyword1'] && $params['field1'] == 1) {
                $where['goods_id'] = $params['keyword1'];
            } else if ($params['keyword1'] && $params['field1'] = 2) {
                $results = SearchGoods::searchEntrance(['title' => $params['keyword1'], 'source' => esGoods::SOURCE_SHOP_ADMIN], esGoods::SCENES_SHOP_ADMIN_TITLE, 0, 1, '*');
                // todo 搜索切换es待删除
//                $results = searchGoods::searchByConditions(['title' => $params['keyword1']]);
                $where['goods_id'] = $results['rows'];
            }
        }

        if(isset($params['status']) && $params['status']) {
            $time = date('Y-m-d H:i:s');
            if($params['status'] == 1) {
                $where['start_time[>=]'] = $time;
            } else if($params['status'] == 2) {
                $where['start_time[<=]'] = $time;
                $where['end_time[>=]'] = $time;
            } else if($params['status'] == 3) {
                $where['end_time[<=]'] = $time;
            }
        }

        return $where;
    }

	public static function admNewComerEditList()
    {
        return mNewComer::getInfo();
    }

	public static function admSaveNewComer($params, $adminId)
    {
        $list = [
            'goods_icon_id' => $params['goods_icon_id'],
            'goods_banner_id' => $params['goods_banner_id'],
            'link_type' => $params['link_type'],
            'link_url' => $params['link'],
            'admin_id' => $adminId
        ];

        $result = mNewComer::saveNewComer($list, $params['newcomer_id']);

        return $result;
    }

    public static function admDownLoad($params)
    {
        $where = self::buildWhere($params);
        $defaultWhere = ['status' =>
            [mNewCommerExclusive::STATUS_NORMAL, mNewCommerExclusive::STATUS_NO_PRICE]
        ];

        if($where) {
            $defaultWhere = array_merge($defaultWhere, $where);
        }

        $infoList = mNewCommerExclusive::select('*', [
            'AND' => $defaultWhere,
            'ORDER' => ['id'=> 'DESC'],
        ]);

        $skuList = mNewCommerExclusiveSku::select('*', [
            'exclusive_id' => array_column($infoList, 'id'),
            'status' => [
                mNewCommerExclusive::STATUS_NORMAL,
                mNewCommerExclusive::STATUS_NO_PRICE
            ],
            'ORDER' => ['end_time'=> 'DESC'],
        ]);

        $priceList = [];
        foreach ($skuList as $value) {
            $priceList[$value['exclusive_id']][] = $value['activity_price'];
        }

        $goodsInfos = Goods::Goods(array_column($infoList, 'goods_id'), Goods::FIELDS_GROUP_DETAIL);
        $skuInfos = sSku::Sku(array_column($infoList, 'goods_id'), sSku::FIELDS_GROUP_SKU_INFO);

        $list = [];
        foreach ($infoList as $value) {
            if (isset($goodsInfos[$value['goods_id']])) {

                $list[] = [
                    'shop_id' => $goodsInfos[$value['goods_id']]['shop_info']['shop_id'],
                    'shop_name' => $goodsInfos[$value['goods_id']]['shop_info']['shop_name'],
                    'goods_id' => $value['goods_id'],
                    'title' => $goodsInfos[$value['goods_id']]['title'],
                    'start_time' => $value['start_time'],
                    'end_time' => $value['end_time'],
                    'activity_min_price' => min($priceList[$value['id']]),
                    'stock' => array_sum(array_column($skuInfos[$value['goods_id']], 'stock')),
                    'status' => $goodsInfos[$value['goods_id']]['status'] == 1 ? '上架' : ($goodsInfos[$value['goods_id']]['status'] == 10 ? '下架' : '已删除')
                ];
            }

        }

        NewComerExcel::downList($list);
        return true;
    }

    public static function saveTime($id, $goodsId, $startTime, $endTime)
    {
        $result = AllactivityInfoBak::admCheckActivityTime([$goodsId], ['start_time' => $startTime, 'end_time' => $endTime], AllactivityInfoBak::ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE , $id);
        if(in_array($goodsId, $result[0])) {
            return mNewCommerExclusive::action(function () use ($id, $goodsId, $startTime, $endTime) {
                $result = mNewCommerExclusive::update([
                    'start_time' => $startTime,
                    'end_time' => $endTime,
                    'edit_time' => date('Y-m-d H:i:s')
                ], [
                    'id' => $id
                ]);
                if ($result->rowCount()) {
                    $result = mNewCommerExclusiveSku::update([
                        'edit_time' => date('Y-m-d H:i:s'),
                        'start_time' => $startTime,
                        'end_time' => $endTime
                    ], [
                        'exclusive_id' => $id,
                    ]);
                    if (!$result->rowCount()) {
                        throw new \Exception('sku数据库更新失败');
                    }

                    $activityData[] = [
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                        'real_start_time' => $startTime,
                        'real_end_time' => $endTime
                    ];

                    return AllActivityInfo::admUpdateActivityAttr($id, AllActivityInfo::ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE, $activityData, AllActivityInfo::ALL_ACTIVITY_TYPE_NEWCOMER_EXCLUSIVE);
                } else {
                    throw new \Exception('数据库更新失败');
                }
            });
        } else {
            return '该商品与以下活动时间重叠 活动ID' . $result[1]['activity_id'] .'活动类型' . AllactivityInfoBak::ACTIVITY_TYPES_MAPS[$result[1]['type']];
        }
    }
}